package net.bxx2004.pandalibloader;

import net.md_5.bungee.api.ProxyServer;
import org.bukkit.Bukkit;

import javax.swing.*;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;

public class ServerUtils {
    static {
        setLibs();
        File f = new File("plugins/PandaLib.jar");
        if (!f.exists()){
            message("§b[§f PandaLibLoader §b] §f- §7没有发现前置 §bPandaLib §7正在为你下载,请稍后...");
            try {
                download();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
    public static PandaLibPlayer player(Object ob){
        return new PandaLibPlayer(ob);
    }
    /**
     * 获取当前服务器类型
     * @return 服务器类型
     */
    public static ServerType server(){
        try {
            Class.forName("org.bukkit.Bukkit");
            return ServerType.BUKKIT;
        }catch (Exception e){
        }
        try {
            Class.forName("net.md_5.bungee.api.ProxyServer");
            return ServerType.BUNGEECORD;
        }catch (Exception e){

        }
        return ServerType.UNKONW;
    }

    /**
     * 向控制台发送消息
     * @param message 消息
     */
    public static void message(String message){
        if (server() == ServerType.BUKKIT){
            Bukkit.getServer().getConsoleSender().sendMessage(message.replaceAll("&","§"));
            return;
        }
        if (server() == ServerType.BUNGEECORD){
            ProxyServer.getInstance().getConsole().sendMessage(message.replaceAll("&","§"));
            return;
        }
        System.out.println(message.replaceAll("&",""));
    }
    private static String loopJar(String name){
        File file = new File("plugins/PandaLib/libs/" + name + ".jar");
        if (file.exists()){
            return file.getAbsolutePath();
        }else {
            return null;
        }
    }
    private static void setLibs(){
        try {
            URL[] urls = new URL[]{
                    new URL("http://linyanmc.cn/libs/kotlin-reflect.jar"),
                    new URL("http://linyanmc.cn/libs/kotlin-stdlib.jar"),
                    new URL("http://linyanmc.cn/libs/kotlin-stdlib-jdk7.jar"),
                    new URL("http://linyanmc.cn/libs/kotlin-stdlib-jdk8.jar"),
                    new URL("http://linyanmc.cn/libs/kotlin-test.jar")
            };
            String[] paths = new String[]{
                    "plugins/PandaLib/libs/kotlin-reflect.jar",
                    "plugins/PandaLib/libs/kotlin-stdlib.jar",
                    "plugins/PandaLib/libs/kotlin-stdlib-jdk7.jar",
                    "plugins/PandaLib/libs/kotlin-stdlib-jdk8.jar",
                    "plugins/PandaLib/libs/kotlin-test.jar"
            };
            File file = new File("plugins/PandaLib/libs");
            if (!file.exists()){
                file.mkdirs();
            }
            if (loopJar("kotlin-reflect") == null){
                download(urls[0],paths[0]);
            }
            if (loopJar("kotlin-stdlib") == null){
                download(urls[1],paths[1]);
            }
            if (loopJar("kotlin-stdlib-jdk7") == null){
                download(urls[2],paths[2]);
            }
            if (loopJar("kotlin-stdlib-jdk8") == null){
                download(urls[3],paths[3]);
            }
            if (loopJar("kotlin-test") == null){
                download(urls[4],paths[4]);
            }
        }catch (Exception e){
            e.printStackTrace();
        }
    }
    /**
     * 下载PandaLib的方法
     */
    public static void download(){
        new Thread(() -> {
            try {
                URL url = null;
                File file = new File("plugins/PandaLib.jar");
                if (server() == ServerType.BUKKIT){
                    url = new URL("http://linyanmc.cn/PandaLib/PandaLib-Bukkit.jar");
                }
                if (server() == ServerType.BUNGEECORD){
                    url = new URL("http://linyanmc.cn/PandaLib/PandaLib-BungeeCord.jar");
                }
                if (server() == ServerType.UNKONW){
                    message("§b[§f PandaLibLoader §b] §f- §7未知的服务端类型,无法下载对应版本的 PandaLib,请前往官网手动下载对应版本");
                }
                HttpURLConnection httpConnection = (HttpURLConnection) (url.openConnection());
                long completeFileSize = httpConnection.getContentLength();
                BufferedInputStream in = new BufferedInputStream(httpConnection.getInputStream());
                FileOutputStream fos = new FileOutputStream(file);
                BufferedOutputStream bout = new BufferedOutputStream(fos, 1024);
                byte[] data = new byte[1024];
                long downloadedFileSize = 0;
                int x = 0;
                while ((x = in.read(data, 0, 1024)) >= 0) {
                    downloadedFileSize += x;
                    final int currentProgress = (int) ((((double)downloadedFileSize) / ((double)completeFileSize)) * 100d);
                    SwingUtilities.invokeLater(new Runnable() {
                        @Override
                        public void run() {
                            System.out.println();
                            message("§b[§f PandaLibLoader §b] §f- §7下载进度: §f"+ currentProgress +"%§7...");
                            if (currentProgress == 100){
                                message("§b[§f PandaLibLoader §b] §f- §7PandaLib下载完成,请重新启动服务器...");
                            }
                        }
                    });

                    bout.write(data, 0, x);
                }
                bout.close();
                in.close();
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }).run();
    }
    public static void sendPluginMessage(String... message){
        if (server() == ServerType.BUKKIT){
            ByteArrayOutputStream b = new ByteArrayOutputStream();
            DataOutputStream out = new DataOutputStream(b);
            try {
                for (String m : message){
                    out.writeUTF(m);
                }
            } catch (Exception e) {

            }
            Bukkit.getServer().sendPluginMessage(Bukkit.getPluginManager().getPlugin("PandaLib"), "BungeeCord",b.toByteArray());
        }
    }
    public static void download(URL url,String path){
        new Thread(() -> {
            try {
                File file = new File(path);
                HttpURLConnection httpConnection = (HttpURLConnection) (url.openConnection());
                long completeFileSize = httpConnection.getContentLength();
                BufferedInputStream in = new BufferedInputStream(httpConnection.getInputStream());
                FileOutputStream fos = new FileOutputStream(file);
                BufferedOutputStream bout = new BufferedOutputStream(fos, 1024);
                byte[] data = new byte[1024];
                long downloadedFileSize = 0;
                int x = 0;
                while ((x = in.read(data, 0, 1024)) >= 0) {
                    downloadedFileSize += x;
                    final int currentProgress = (int) ((((double)downloadedFileSize) / ((double)completeFileSize)) * 100d);
                    SwingUtilities.invokeLater(new Runnable() {
                        @Override
                        public void run() {
                            System.out.println();
                            message("§b[§f PandaLibLoader §b] §f- §7下载进度: §f"+ currentProgress +"%§7...");
                            if (currentProgress == 100){
                                message("§b[§f PandaLibLoader §b] §f- §7下载完成...");
                                if (server() == ServerType.BUKKIT){
                                    Bukkit.getServer().shutdown();
                                }
                                if (server() == ServerType.BUNGEECORD){
                                    ProxyServer.getInstance().stop();
                                }
                            }
                        }
                    });

                    bout.write(data, 0, x);
                }
                bout.close();
                in.close();
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }).run();
    }
}

